import { defineStore } from 'pinia'
import { OrderAPI, type Order, type OrderQuery } from '@/api/order'

// 定义API响应类型
interface ApiResponse<T = any> {
    code: number
    data: T
    message?: string
}

interface OrderListResponse {
    list: Order[]
    total: number
    page: number
    pageSize: number
}

export const useOrderStore = defineStore('order', {
    state: (): OrderState => ({
        orders: [],
        currentOrder: null,
        loading: false,
        total: 0,
        page: 1,
        pageSize: 10,
        query: {}
    }),

    getters: {
        // 获取订单列表
        getOrders: (state) => state.orders,
        // 获取当前订单
        getCurrentOrder: (state) => state.currentOrder,
        // 获取加载状态
        getLoading: (state) => state.loading,
        // 获取分页信息
        getPagination: (state) => ({
            total: state.total,
            page: state.page,
            pageSize: state.pageSize
        }),
        // 获取查询条件
        getQuery: (state) => state.query
    },

    actions: {
        // 获取订单列表（读操作 - DU读）
        async fetchOrders(query: OrderQuery = {}) {
            this.loading = true
            try {
                const params = { ...this.query, ...query, page: this.page, pageSize: this.pageSize }
                const response = await OrderAPI.getOrderList(params) as unknown as ApiResponse<OrderListResponse>

                if (response.code === 200) {
                    this.orders = response.data.list
                    this.total = response.data.total
                    this.page = response.data.page
                    this.pageSize = response.data.pageSize
                }
            } catch (error) {
                console.error('获取订单列表失败:', error)
                throw error
            } finally {
                this.loading = false
            }
        },

        // 获取订单详情（读操作 - DU读）
        async fetchOrderDetail(id: number) {
            this.loading = true
            try {
                const response = await OrderAPI.getOrderDetail(id) as unknown as ApiResponse<Order>

                if (response.code === 200) {
                    this.currentOrder = response.data
                }
            } catch (error) {
                console.error('获取订单详情失败:', error)
                throw error
            } finally {
                this.loading = false
            }
        },

        // 创建订单（写操作 - XIE写）
        async createOrder(order: Omit<Order, 'id' | 'createTime' | 'updateTime'>) {
            this.loading = true
            try {
                const response = await OrderAPI.createOrder(order) as unknown as ApiResponse<Order>

                if (response.code === 200) {
                    // 创建成功后刷新列表
                    await this.fetchOrders()
                    return response.data
                }
            } catch (error) {
                console.error('创建订单失败:', error)
                throw error
            } finally {
                this.loading = false
            }
        },

        // 更新订单（写操作 - XIE写）
        async updateOrder(id: number, order: Partial<Order>) {
            this.loading = true
            try {
                const response = await OrderAPI.updateOrder(id, order) as unknown as ApiResponse<Order>

                if (response.code === 200) {
                    // 更新成功后刷新列表
                    await this.fetchOrders()
                    return response.data
                }
            } catch (error) {
                console.error('更新订单失败:', error)
                throw error
            } finally {
                this.loading = false
            }
        },

        // 删除订单（写操作 - XIE写）
        async deleteOrder(id: number) {
            this.loading = true
            try {
                const response = await OrderAPI.deleteOrder(id) as unknown as ApiResponse<any>

                if (response.code === 200) {
                    // 删除成功后刷新列表
                    await this.fetchOrders()
                }
            } catch (error) {
                console.error('删除订单失败:', error)
                throw error
            } finally {
                this.loading = false
            }
        },

        // 更新订单状态（写操作 - XIE写）
        async updateOrderStatus(id: number, status: Order['status']) {
            this.loading = true
            try {
                const response = await OrderAPI.updateOrderStatus(id, status) as unknown as ApiResponse<Order>

                if (response.code === 200) {
                    // 更新成功后刷新列表
                    await this.fetchOrders()
                    return response.data
                }
            } catch (error) {
                console.error('更新订单状态失败:', error)
                throw error
            } finally {
                this.loading = false
            }
        },

        // 获取订单统计（读操作 - DU读）
        async fetchOrderStats() {
            this.loading = true
            try {
                const response = await OrderAPI.getOrderStats() as unknown as ApiResponse<any>
                return response.data
            } catch (error) {
                console.error('获取订单统计失败:', error)
                throw error
            } finally {
                this.loading = false
            }
        },

        // 设置查询条件
        setQuery(query: OrderQuery) {
            this.query = query
        },

        // 设置分页
        setPagination(page: number, pageSize: number) {
            this.page = page
            this.pageSize = pageSize
        },

        // 重置状态
        reset() {
            this.orders = []
            this.currentOrder = null
            this.loading = false
            this.total = 0
            this.page = 1
            this.pageSize = 10
            this.query = {}
        }
    }
})

interface OrderState {
    orders: Order[]
    currentOrder: Order | null
    loading: boolean
    total: number
    page: number
    pageSize: number
    query: OrderQuery
} 